package com.powerunion.datacollection.web.struts;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.model.MaintblData;
import com.powerunion.datacollection.model.SubFormSet;
import com.powerunion.datacollection.service.CascadeFieldManager;
import com.powerunion.datacollection.service.SubFormDataManager;
import com.powerunion.datacollection.service.SubFormSetManager;
import com.powerunion.datacollection.transaction.Transaction;
import com.powerunion.datacollection.transaction.TransactionHelper;
import com.powerunion.util.log.LogHelper;

public class SubFormSetAction extends BaseAction {

	private static final Logger logger = LogHelper.getInstance().getLogger(
			SubFormSetAction.class);
	private SubFormSetManager formSetManager = null;
	private SubFormDataManager formDataManager = null;

	public SubFormSetAction() {
		super();
		this.formSetManager = new SubFormSetManager();
		this.formDataManager = new SubFormDataManager();
	}

	public void finalize() throws Throwable {
		this.formSetManager = null;
		this.formDataManager = null;
		super.finalize();
	}

	/**
	 * 加载主从表外键关联设置信息
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getCascadeFields(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String formId = request.getParameter("formId");
		CascadeFieldManager cfm = new CascadeFieldManager();
		List fields = cfm.getCascadeFields(formId);
		JSONArray jsonArr = JSONArray.fromObject(fields);
		String result = "{results:"+jsonArr+"}";
		logger.debug("getCascadeFields:"+result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	/**
	 * 加载从表设置信息
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward loadSubInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String id = request.getParameter("id");
		response.setContentType("text/json;charset=utf-8");
		String data = this.formSetManager.loadSubInfo(id);
		logger.debug("loadInfo the sub FormSet:" + data);
		response.getWriter().print(data);
		return null;
	}
	
	/**
	 * 加载主表设置信息
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward loadMaintInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String formId = request.getParameter("id");
		response.setContentType("text/json;charset=utf-8");
		String data = this.formSetManager.loadMaintInfo(formId);
		logger.debug("loadInfo the maint FormSet:" + data);
		response.getWriter().print(data);
		return null;
	}

	public ActionForward getFieldNames(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String tableName = request.getParameter("id");
		String svrName = request.getParameter("svrName");
		String result = "";
		result = this.formSetManager.getFieldNames(svrName, tableName);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	public ActionForward getFields4MaintTbl(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String formId = request.getParameter("formId");
		SubFormSet mf = this.formSetManager.findFormSetByKey4MaintTbl(formId);
		String result = "";
		result = this.formSetManager.getFields(mf);
		logger.debug("getFields4MaintTbl:"+result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	public ActionForward getMaintblDataInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String formId = request.getParameter("formId");
		String submiUser = request.getRemoteUser();
		String procId = request.getParameter("procId");
		String actId = request.getParameter("actId");
		
		MaintblData data = new MaintblData();
		data.setFormId(formId);
		data.setSubmiUser(submiUser);
		data.setProcId(procId);
		data.setActId(actId);
		
		String result = "";
		result = this.formDataManager.getMaintblDataInfo4SubFormMaintTbl(data,Constants.FORM_DATA_TYPE_SAVE);
		logger.debug("getMaintblDataInfo:"+result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	public ActionForward getFields4SubTbl(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String formId = request.getParameter("formId");
		SubFormSet sf = this.formSetManager.findFormSetByKey4SubTbl(formId);
		String result = "";
		result = this.formSetManager.getFields(sf);
		logger.debug("getFields4SubTbl:"+result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	public ActionForward getServerFields(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String svrName = request.getParameter("svrName");
		String tableName = request.getParameter("tableName");
		String result = "";
		result = this.formSetManager.getServersFields(svrName, tableName);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	public ActionForward getServerTables(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String svrName = request.getParameter("svrName");
		String result = "";
		result = this.formSetManager.getServerTables(svrName);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	public ActionForward getComboFields(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String svrName = request.getParameter("svrName");
		String tblName = request.getParameter("tblName");
		String itemLabel = request.getParameter("itemLabel");
		String itemValue = request.getParameter("itemValue");
		String result = "";
		result = this.formSetManager.getComboFields(svrName, tblName, itemLabel, itemValue);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	public ActionForward getSubFormSetDataSourceTree(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String formId = request.getParameter("formId");
		String syrName = request.getParameter("node");
		JSONArray jsonArray = new JSONArray();
		response.setContentType("text/json;charset=utf-8");
		jsonArray = this.formSetManager.getSubFormSetDataSourceTree(formId,syrName);
		try {
			response.getWriter().print(jsonArray);
		} catch (IOException e) {
			logger.error("输出json失败" ,e);
			return null;
		}
		return null;
	}
	
	public ActionForward save4SubTbl(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		SubFormSetForm subFormSetForm = (SubFormSetForm)form;
		SubFormSet subFormSet = subFormSetForm.getFormSet();
		Transaction transaction = null;
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();

			boolean isSuccess = false;
			isSuccess = this.formSetManager.save4SubTbl(subFormSet);  
	
			if (isSuccess) {
				this.renderSuccssJson(response);
			} else {
				this.renderFAILUREJson(response);
			}

			transaction.commit();
		} catch (Exception e) {
			try {
				logger.error("", e);
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				this.renderFAILUREJson(response);
			}
		}

		return null;
	}
	
	public ActionForward save4MaintTbl(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String saveStr = request.getParameter("formData");
		Transaction transaction = null;
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();
			logger.debug("save4MaintTbl主表信息:" +saveStr);

			boolean isSuccess = false;
			isSuccess = this.formSetManager.save(saveStr); 
	
			if (isSuccess) {
				this.renderSuccssJson(response);
			} else {
				this.renderFAILUREJson(response);
			}

			transaction.commit();
		} catch (Exception e) {
			try {
				logger.error("", e);
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				this.renderFAILUREJson(response);
			}
		}

		return null;
	}
}
